package com.xiaohai.aop;

import com.xiaohai.projo.Log;
import com.xiaohai.service.LogService;
import com.xiaohai.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * ClassName:LoginAdvice
 * Package:IntelliJ IDEA
 * Description:
 * Author 何诗海
 *
 * @Create 2024/2/24 11:21
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
public class LogAdvice {
    @Autowired
    private LogService logService;
    @Autowired
    private HttpServletRequest request;

    @Around("execution(* com.xiaohai.controller.*.*(..))")
    public Object logAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        String name = joinPoint.getSignature().getName();
        long star = System.currentTimeMillis();
        Object o = joinPoint.proceed();
        long end = System.currentTimeMillis();


        String url = request.getRequestURL().toString();
        Log log1 = new Log();
        String account = (String) request.getSession().getAttribute("account");
        log1.setDes("账户:" + account + "在"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) +"登录了系统");
      if(url.contains("/login")){
          logService.insert(log1);
      }

        log.info(name + "接口，耗时：" + (end - star) + "毫秒");
        return o;
    }

    @AfterThrowing(value = "execution(* com.xiaohai.controller.*.*(..))",throwing = "ex")
    public void logAfterThrowing(JoinPoint joinPoint, Exception ex) {
        String url = request.getRequestURL().toString();
        Log log1 = new Log();
        String account = (String) request.getSession().getAttribute("account");
        log1.setDes("账户:" + account + "执行了" + url + "接口操作发生了异常,异常信息:"+ex.getMessage());
        logService.insert(log1);
    }
}